import { createRouter, createWebHashHistory, RouteLocationNormalized, RouteRecordRaw } from 'vue-router'
import { jilurizhi } from '../api'
import activity from './views/Activity/activity.vue'
import Activityindex from './views/Activity/index.vue'
import Home from './views/Home.vue'
import index from './views/index.vue'
import Login from './views/login.vue'
import match from './views/match/index.vue'
import matchend from './views/match/matchend.vue'
import matchindex from './views/match/matchindex.vue'
import matchquestion from './views/match/matchquestion.vue'

function toID(rote: RouteLocationNormalized): Record<string, any> {
  return {
    ID: Number(rote.params.ID)
  }

}

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: '主页',
    component: index,
    // 主页默认进入首页
    redirect: to => {
      return { name: '首页' }
    },
    children: [
      {
        path: 'home',
        name: '首页',
        component: Home,
        props: (route) => ({
          activityId: Number(route.query.activityId) || 1
        })
      },
      // nav-比赛
      {
        path: 'activity',
        name: '竞赛',
        component: Activityindex
      },
      {
        path: 'activity/:ID',
        name: '比赛详情',
        component: activity,
        props: toID
      },
      {
        path: 'match/:ID',
        name: '比赛',
        component: match,
        redirect: {
          name: '比赛首页'
        },
        props: toID,
        children: [
          {
            name: '比赛首页',
            path: 'index',
            component: matchindex,
          },
          {
            name: '比赛答题',
            path: 'question/:index',
            component: matchquestion,
            props: true
          },
          {
            name: '比赛结束',
            path: 'matchend',
            component: matchend,
          }
        ]
      }
    ]
  },
  {
    path: '/login',
    name: '登录',
    component: Login
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

router.beforeEach(async (to, from, next) => {
  // 登录者信息
  // const online = sessionStorage.getItem('online')
  // try {
  //   if (to.path !== '/login') {
  //     const onlineRet = await online()
  //   }
  next()
  // } catch (error) {
  //   console.error("beforeEach onlineRet error=>", error)
  //   next('/login')
  // }
})

router.afterEach((to, from) => {
  const arr: [string, string][] = []
  arr[0] = ['type', 'router']
  arr[1] = ['typename1', to.name ? String(to.name) : '']
  arr[2] = ['__from__', from.name ? String(from.name) : '']
  jilurizhi(arr)
})

export default router
